const global = require('../global')
const path = require('path')
const util = require('../util')
const fs = require('fs-extra')

const ignore = ['img', 'code']
const createLine = (name, index, url) => `${new Array(index).fill('  ').join('')}* [${name}](${url.replace(/\\/g, '/')})\n`

function getSideBar(url, newPath, name, index) {
  if (util.isExists(newPath)) {
    if (ignore.includes(name)) return
    const isDirectory = util.isDirectory(newPath)
    let content = createLine(name, index, isDirectory ? '' : path.relative(url, newPath))
    if (isDirectory) {
      content += fs.readdirSync(newPath).map(p => {
        return getSideBar(url, path.join(newPath, p), p, index + 1)
      }).filter(t => !!t).join('')
    }
    return content
  }
}

module.exports = (url, [docs, name]) => {
  return getSideBar(path.join(global.root, `${docs}/${name}`), path.resolve(global.docs, name), name, 0)
}